package bfa.gps;

import java.util.ArrayList;
import java.util.Iterator;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.GpsStatus.Listener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;



public class LocalService extends Service implements Listener {
	@Override
	public IBinder onBind(Intent intent) {
		return new LocalBinder<LocalService>(this);
	}
	
	
//	/**
//     * Class used for the client Binder.  Because we know this service always
//     * runs in the same process as its clients, we don't need to deal with IPC.
//     */
//    public class LocalBinder extends Binder {
//        LocalService getService() {
//            // Return this instance of LocalService so clients can call public methods
//            return LocalService.this;
//        }
//    }

	
	private Handler handler=null;
	public void setHandler(Handler handler) {
	    this.handler=handler;
	}
	
	

	private void notifyMessage(String propName,String str) {
		 if (handler!=null) {
		    Message msg = handler.obtainMessage();
		    Bundle b = new Bundle();
		    b.putString(propName, ""+str);
		    msg.setData(b);
		    handler.sendMessage(msg);
		  }
	 }
	
	
	
	
	
	private class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			//super.handleMessage(msg);
			
			if (handler!=null && msg!=null) {

			    Message msg2 = handler.obtainMessage();
			    //Bundle b = new Bundle();
			    //b.putString(msg.getD, ""+str);
			    msg2.setData(msg.getData());
			    handler.sendMessage(msg2);
			}
			/*Bundle bundle = msg.getData();
			if (bundle.containsKey("gpsProvider")) {
				String value = bundle.getString("gpsProvider");
			}
			if (bundle.containsKey("gpsStatus")) {
				String value = bundle.getString("gpsStatus");
			}*/
		}
	}
	
	LocationManager locManager;
	MyLocationListener locListener;
	@Override
	public void onCreate() {
		Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
		

		Handler handler = new MyHandler();

        
        locManager=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locListener=new MyLocationListener(handler);
        locListener.appCon =getApplicationContext();
        locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, locListener);
        locManager.addGpsStatusListener(this);
        
    	boolean gps_on = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    	if (gps_on) {
        	notifyMessage("gpsProvider", "enabled");
        	
    	} else {
    		notifyMessage("gpsProvider", "disabled");
        	
    	}

		
	}
	
	@Override
	public boolean onUnbind(Intent intent) {
		Toast.makeText(this, "My Service unbind", Toast.LENGTH_LONG).show();
	    return true;
	}
	

	@Override
	public void onDestroy() {
		Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
	}
	
	@Override
	public void onStart(Intent intent, int startid) {
		Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
	}

	public boolean hasFix=false;
	private ArrayList<GpsSatellite> satellites=new ArrayList<GpsSatellite>();
	
	@Override
	public void onGpsStatusChanged(int arg0) {
		GpsStatus status= locManager.getGpsStatus(null);	
			
		if (arg0==GpsStatus.GPS_EVENT_SATELLITE_STATUS && someBodyListening) {
			
			getSatellites().clear();
			hasFix=false;
			
	        Iterable<GpsSatellite> iSatellites = status.getSatellites() ; 
	        Iterator<GpsSatellite> it = iSatellites.iterator() ; 
	        while ( it.hasNext() )  {
	        	 GpsSatellite oSat = (GpsSatellite) it.next() ;
	        
	        	 if (oSat.usedInFix()) {
	        		 hasFix=true;
	        	 }
	        	 
	        	 getSatellites().add(oSat);
//	        	 
//	        	 if(oSat.usedInFix()){
//                    Log.e("A fost folosit ", "int fix!");
//                }
//                if(oSat.toString()!=null){
//                    Log.e("Test", "SNR:"+oSat.getSnr()+"; Azimuth:"+oSat.getAzimuth()+"; Elevation:"+oSat.getElevation()+" "+oSat.toString()+"; PRN:"+oSat.getPrn());
//                }

	        }
			notifyMessage("satUpdate", "" );
			
		}
		
		if (arg0==GpsStatus.GPS_EVENT_FIRST_FIX) {
			notifyMessage("firstFix", new Integer(status.getTimeToFirstFix()/1000).toString() );
		}
			
		
		
	}

	private boolean someBodyListening=false;
	public void setSomeBodyListening(boolean someBodyListening) {
		this.someBodyListening = someBodyListening;
	}



	public ArrayList<GpsSatellite> getSatellites() {
		return satellites;
	}

}